#import "SEGOnefileuploadManager.h"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

static id _oneFileUploadManager;
static dispatch_once_t onceToken;

@interface SEGOnefileuploadManager()
@property (nonatomic, copy, readwrite) NSString *urlString;
@end

@implementation SEGOnefileuploadManager
#pragma mark - SINGLE----BEGIN----
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _oneFileUploadManager = [[self alloc] init];
    });
    return _oneFileUploadManager;
}

+(void)destroyResource{
    onceToken = 0;
    _oneFileUploadManager = nil;
}

#pragma mark - SINGLE----END----

#pragma mark - HTTP----BEGIN----
-(void)requestOnefileuploadWithData:(NSData*)data name:(NSString*)name progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    [SEGHTTPBusinessManager seg_uploadImageWithURLString:self.urlString parameters:nil source:data fileName:name progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error);
            return;
        }
        
        self.oneFileUpload = [SEGOnefileuploadModel yy_modelWithDictionary:result];
        completed(YES,result,codeType,error);
        return;
    }];
}

-(void)requestOnefileuploadWithData:(NSData*)data progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    
    [SEGHTTPBusinessManager seg_uploadImageWithURLString:self.urlString parameters:nil source:data progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error);
            return;
        }
        
        self.oneFileUpload = [SEGOnefileuploadModel yy_modelWithDictionary:result];
        completed(YES,result,codeType,error);
        return;
    }];
}

/**
 图片上传-单图
 
 @author Sam
 @param data 图片二进制
 @param progress 上传进度回调
 @param completed 完成上传回调
 */
-(void)requestOnefileuploadWithImage:(UIImage*)img progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    
    //调正图片方向
    UIImage* image = [SEGUtils fixOrientation:img];
    
    //压缩图片
    CGFloat hh = MAX(image.size.width, image.size.height);
    UIImage *scaleImageView = nil;
    if (hh>1280)
    {
        CGFloat wh = 1280/hh;
        scaleImageView = [SEGUtils OriginImage:image scaleToSize:CGSizeMake(image.size.width*wh, image.size.height*wh)];
    }
    else
    {
        scaleImageView = [SEGUtils OriginImage:image scaleToSize:CGSizeMake(image.size.width, image.size.height)];
    }
    
    NSData *data = UIImageJPEGRepresentation(scaleImageView, 0.8);//获取图片数据
    
    [self requestOnefileuploadWithData:data progress:progress completed:completed];
}

/// 上传人脸识别图片（后台会对图片做校验）
/// @param image image
/// @param serviceType 0：b端服务，1：c端服务
/// @param completed completed
- (void)requestImageUploadToCheckFaceDetection:(UIImage *)image serviceType:(NSString*)serviceType completed:(SEGReponseBlock)completed {
    
    // 压缩图片到1.3M以内
    NSData *imageData = [SEGUtils compressImageQuality:image maxLength:1.3*1024*1024];
    NSLog(@"Size of Image(bytes):%lu",(unsigned long)[imageData length]);
    
    /// serviceType 0：b端服务，1：c端服务
    NSString *faceDetectionURL = [SEGServerManager serverUrlJoint:kClientRootURL,@"/enterprise-app/faceDetection/checkFaceDetectionImage",nil];
    if ([serviceType isEqualToString:@"0"]) faceDetectionURL = [faceDetectionURL stringByReplacingOccurrencesOfString:kClientRootURL withString:kBrowerRootURL];
    
    [SEGHTTPBusinessManager seg_uploadImageWithURLString:faceDetectionURL parameters:nil source:imageData progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error);
            return;
        }
        
        self.oneFileUpload = [SEGOnefileuploadModel yy_modelWithDictionary:result];
        completed(YES,result,codeType,error);
        return;
    }];
}

#pragma mark - HTTP----END----

/**
 调整图片大小在指定的Bytes以内
 
 @param lenght byte
 @param img source
 */
-(NSData*)adjustImageWithinLenght:(CGFloat)lenght imge:(UIImage*)img{
    NSData  * data = UIImageJPEGRepresentation(img, 1);
    if (data.length <= lenght) return  data;
    
    data = UIImageJPEGRepresentation(img, 0.1);
    if (data.length >= lenght) return  data;
    
    CGFloat maxQuality = 1.0;
    CGFloat minQuality = 0.0;
    int flag = 0;
    
    while (1) {
        CGFloat midQuality = (maxQuality + minQuality)/2.0;
        data = UIImageJPEGRepresentation(img, midQuality);
        flag ++;
        
        if (flag == 6) return data;
        
        if (data.length > lenght)  {
            maxQuality = midQuality;
            continue;;
        }
        
        if (data.length < lenght)  {
            minQuality = midQuality;
            continue;
        }
        
        return data;
    }
}

#pragma mark - GETTER----BEGIN----
-(SEGOnefileuploadModel *)oneFileUpload{
    if (!_oneFileUpload) {
        _oneFileUpload = [[SEGOnefileuploadModel alloc]init];
    }
    return _oneFileUpload;
}

-(NSString *)urlString{
    if (!_urlString) {
        _urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-app/common/oneFileUpload.json",nil];
    }
    return _urlString;
}
#pragma mark - GETTER----END----
@end
